const router = require('express').Router()
const validateToken = require('../../../../common/validateToken')
const status_code = require('../../../../common/status_code')
const db = require('../../../../db/async-db')
const { to } = require('await-to-js')
const bcrypt = require('bcryptjs')
const Bee = require('../../../../common/bee/bee')

router.post('/update', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error('错误：', error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const {
    id,
    name,
    parent_id,
    node_type,
    link_url,
    menu_status,
    sort,
    level,
    icon_url,
    selected_icon_url,
    router_name,
  } = req.body
  if (
    !Bee.StringUtils.isNumber(id) ||
    !Bee.StringUtils.isNumber(parent_id) ||
    !Bee.StringUtils.isNumber(node_type) ||
    !Bee.StringUtils.isNumber(menu_status) ||
    !Bee.StringUtils.isNumber(parseInt(sort)) ||
    !Bee.StringUtils.isNotBlank(name)
  )
    return handleError(10003, '参数错误')

  if (node_type === 2 && !Bee.StringUtils.isNotBlank(link_url))
    return handleError(10003, '参数错误')

  const [findMenuError, MenuList] = await to(
    db.query('SELECT * FROM menu WHERE id=?', [parent_id])
  )
  console.log(MenuList)
  if (findMenuError || !MenuList || (parent_id !== 0 && MenuList.length !== 1))
    return handleError(-1, findMenuError)
  const Menu = MenuList[0]

  const [updateMenuError, updateMenu] = await to(
    db.query(
      'UPDATE menu SET name=?, parent_id=?, node_type=?, link_url=?, path=?, menu_status=?, sort=?, level=?, icon_url=?, selected_icon_url=?, router_name=? WHERE id=?;',
      [
        name,
        parent_id,
        node_type,
        node_type === 1 ? '' : link_url,
        `${Menu && Menu.path ? Menu.path : ''}${
          Menu && Menu.path && Menu.path !== '' ? ',' : ''
        }${parent_id}`,
        menu_status,
        parseInt(sort),
        Menu && Menu.level ? (Menu.level += 1) : level,
        icon_url ? icon_url : '',
        selected_icon_url ? selected_icon_url : '',
        router_name ? router_name : '',
        id,
      ]
    )
  )

  if (updateMenuError || !updateMenu || updateMenu.affectedRows === 0)
    return handleError(-1, updateMenuError)
  resp.json({
    code: 0,
    msg: status_code[0],
  })
})

module.exports = router
